﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using TruckScale.Helpers;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB1 = null;
    private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB2 = null;

    private void InitLPRProps()
    {
      if (Global._lpr1playHandle > 0)
      {
        int ret = VzClientSDK.VzLPRClient_StopRealPlay(Global._lpr1playHandle);
        Global._lpr1playHandle = 0;
      }
      if (Global._lpr2playHandle > 0)
      {
        int ret = VzClientSDK.VzLPRClient_StopRealPlay(Global._lpr2playHandle);
        Global._lpr2playHandle = 0;
      }
      if (Global._lpr1Handle > 0)
      {
        VzClientSDK.VzLPRClient_Close(Global._lpr1Handle);
        Global._lpr1Handle = 0;
      }
      if (Global._lpr2Handle > 0)
      {
        VzClientSDK.VzLPRClient_Close(Global._lpr2Handle);
        Global._lpr2Handle = 0;
      }
      if (Global._lprSetup == 0)
      {
        VzClientSDK.VzLPRClient_Cleanup();
        Global._lprSetup = -1;
      }
      //VzClientSDK.VzLPRClient_Cleanup();


      Global._lprSetup = VzClientSDK.VzLPRClient_Setup();

      Task.Run(() =>
      {
        if (Convert.ToBoolean(Global._hardwareConfig["LPR1Enable"]))
        {
          Global._lpr1Handle = VzClientSDK.VzLPRClient_Open(Global._hardwareConfig["LPR1IP"], 80, Global._hardwareConfig["LPRUser"], Global._hardwareConfig["LPRPwd"]);
          
          if (Global._lpr1Handle == 0)
          {
            SetLog($"{Global._hardwareConfig["LPR1IP"]}车牌相机打开失败", LogType.HardwareLogger, LogLevel.Error);
          }
          else
          {
            SetLog($"{Global._hardwareConfig["LPR1IP"]}车牌相机打开成功", LogType.HardwareLogger);

            m_PlateResultCB1 = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
            VzClientSDK.VzLPRClient_SetPlateInfoCallBack(Global._lpr1Handle, m_PlateResultCB1, IntPtr.Zero, 1);

            Global._lpr1playHandle = VzClientSDK.VzLPRClient_StartRealPlay(Global._lpr1Handle, Global._wnd5Handle);
          }
        }

        if (Convert.ToBoolean(Global._hardwareConfig["LPR2Enable"]))
        {
          Global._lpr2Handle = VzClientSDK.VzLPRClient_Open(Global._hardwareConfig["LPR2IP"], 80, Global._hardwareConfig["LPRUser"], Global._hardwareConfig["LPRPwd"]);

          if (Global._lpr2Handle == 0)
          {
            SetLog($"{Global._hardwareConfig["LPR2IP"]}车牌相机打开失败", LogType.HardwareLogger, LogLevel.Error);
          }
          else
          {
            SetLog($"{Global._hardwareConfig["LPR2IP"]}车牌相机打开成功", LogType.HardwareLogger);

            m_PlateResultCB2 = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
            VzClientSDK.VzLPRClient_SetPlateInfoCallBack(Global._lpr2Handle, m_PlateResultCB2, IntPtr.Zero, 1);

            Global._lpr2playHandle = VzClientSDK.VzLPRClient_StartRealPlay(Global._lpr2Handle, Global._wnd6Handle);
          }
        }
      });
    }

    private int OnPlateResult(int handle, IntPtr pUserData,
                                                  IntPtr pResult, uint uNumPlates,
                                                  VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType,
                                                  IntPtr pImgFull,
                                                  IntPtr pImgPlateClip)
    {
      if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
      {
        VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
        string strLicense = new string(result.license).TrimEnd('\0');

        if (strLicense == "_无_") return 0;
        if (strLicense == "无牌车") return 0;
        if (strLicense.Contains("挂")) return 0;
        if (weighingStatus == WeighingStatus.InProgress && WeighRecord.Ch != null)
        {
          return 0;
        }

        byte[] strDecIP = new byte[32];
        VzClientSDK.VzLPRClient_GetDeviceIP(handle, ref strDecIP[0], 32);
        string strIP = Encoding.Default.GetString(strDecIP).TrimEnd('\0');

        SetLog($"{strIP} 识别到车牌: {strLicense}", LogType.HardwareLogger);

        //保存图片到临时目录
        string tempPicPath = Path.Combine(Environment.CurrentDirectory, "Snap", "Temp");
        Directory.CreateDirectory(tempPicPath);
        tempPicPath = Path.Combine(tempPicPath, strLicense + ".jpg");
        VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, tempPicPath, 100);

        //根据车牌号查询是否有未完成的记录，并显示到UI过磅单里
        WeighRecord.Ch = strLicense;
        var record = WeighRecordModel.LoadUnexpiredWeighRecord(strLicense, Global._weighConfig["WeighExpiryDate"]);
        if (record != null)
        {
          WeighRecord = record;
        }
        //如果有启用语音，播放语音
        if (Convert.ToBoolean(Global._weighConfig["TTS3Enable"]))
        {
          TTSHelper.TTS(WeighRecord, Global._weighConfig["TTS3Text"]);
        }
        //如果有启用继电器，控制继电器抬杆、变对面方向为红灯
        if (Convert.ToBoolean(Global._hardwareConfig["IOEnable"]))
        {
          if (strIP == Global._hardwareConfig["LPR1IP"])
          {
            Task.Run(async () => {
              Barrier1 = true;
              await Task.Delay(300);
              Light2 = true;
            });
          }

          if (strIP == Global._hardwareConfig["LPR2IP"])
          {
            Task.Run(async () => {
              Barrier2 = true;
              await Task.Delay(300);
              Light1 = true;
            });
          }
        }
        //识别到车牌时，将称重状态改为称重中，不再识别车牌
        weighingStatus = WeighingStatus.InProgress;

        App.Current.Dispatcher.Invoke(() => InitWeighFormProps());
        CheckBtnEnable();
      }

      return 0;
    }
  }
}
